﻿#include "scrollareat1.h"
#include "ui_scrollareat1.h"
#include <QVBoxLayout>
#include <QPushButton>
#include <QScrollArea>
#include "customlistitem.h"
#include <QTimer>


ScrollAreaT1::ScrollAreaT1(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ScrollAreaT1)
{
    ui->setupUi(this);
//    this->ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAlwaysOff);

    QScrollArea* scroll = new QScrollArea();
//    scroll->setMinimumWidth(100);
//    scroll->se(300);
    QVBoxLayout *pLayout = new QVBoxLayout();//网格布局
    CustomListItem *pBtn;
    for(int i = 0; i < 20; i++)
    {
        pBtn = new CustomListItem(CustomListItem::ItemStyle::Column, QString("按钮%1").arg(i), "正手攻球");
        pLayout->addWidget(pBtn);//把按钮添加到布局控件中
    }
    this->ui->scrollArea->setStyleSheet("background:gray;");
    this->ui->scrollArea->widget()->setLayout(pLayout);

    scroll->setStyleSheet("background:black;");

    QVBoxLayout* vLayout = new QVBoxLayout();
    vLayout->addWidget(scroll);
    this->ui->groupBox_2->setLayout(vLayout);


    // 延迟2秒，模拟动态加载数据
    QTimer *t1 = new QTimer();
    t1->start(2000);
    connect(t1, &QTimer::timeout, [=](){
        QVBoxLayout *pLayout = new QVBoxLayout();
        for(int i = 0; i < 20; i++)
        {
            CustomListItem *pBtn1 = new CustomListItem(CustomListItem::ItemStyle::Column, QString("按钮%1").arg(i), "正手攻球");
            pLayout->addWidget(pBtn1);//把按钮添加到布局控件中
        }
        QWidget* widget = new QWidget();
        widget->setLayout(pLayout);//把布局放置到QScrollArea的内部QWidget中
        scroll->setWidget(widget);
        // 该属性决定子元素是否自适应宽搞
        scroll->setWidgetResizable(true);
        t1->stop();
    });


    connect(this->ui->pushButton, &QPushButton::clicked, [=](){
//          scroll->ensureWidgetVisible(pBtn2);

      // 跳转这里有个深坑，
      // 正常会以为 ScrollArea 下widget 控件的Parent 就是ScrollArea 对象，但并不是这样，最终拿到的是“scroll_area_viewport”一个视图控件，也就是说再包装了一层
      // 如果要通过ScrollArea 下的Widget控件拿到ScrollArea，需要获取Parent后再一次获取Parent才行；
      QScrollArea* sa1 =(QScrollArea*)this->ui->scrollArea->widget()->parent();
      QScrollArea* sa2 =(QScrollArea*)this->ui->scrollArea->widget()->parent()->parent();
      sa2->ensureWidgetVisible(pBtn);

      // 通过输出指针地址查看
      qDebug() << sa1 << endl;
      qDebug() << sa2 << endl;
      qDebug() << scroll << endl;

      pBtn->selected();
    });




}

ScrollAreaT1::~ScrollAreaT1()
{
    delete ui;
}
